package com.woniu.service.impl;

import com.alibaba.fastjson2.JSON;
import com.woniu.dao.ClientDao;
import com.woniu.dao.CustomFeedDao;
import com.woniu.entity.Client;
import com.woniu.entity.CustomFeed;
import com.woniu.entity.LoanInfo;
import com.woniu.entity.UserInfoEntity;
import com.woniu.service.CustomFeedService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service

public class CustomFeedServiceImpl implements CustomFeedService {

    @Resource
    @Qualifier("customFeedDao")
    CustomFeedDao customFeedDao;

    @Resource
    @Qualifier("clientDao")
    ClientDao clientDao;

    @Override
    public List<CustomFeed> findAllCustomFeed(CustomFeed customFeed) {
        List<CustomFeed> allCustomFeed = customFeedDao.findAllCustomFeed(customFeed);
        for (CustomFeed c : allCustomFeed) {

            c.setClientId(customFeedDao.getClientIdById(c.getId()));

            c.setApplicantStatus(customFeedDao.getApplicantStatus(c.getAppliedStatus()));
        }
        return allCustomFeed;
    }

    @Override
    public Boolean saveUserInfo(UserInfoEntity userInfo) {
        String jsonStr = JSON.toJSONString(new HashMap<String, String>() {
            {
                put("jsonStr", userInfo.getIJSONString());
            }
        });
        Integer clientId = userInfo.getId();
        String opt = userInfo.getOpt();
        Integer loanId = customFeedDao.getLoanIdByClientId(clientId);
        System.out.println("loanId"+loanId);
        if (opt.equals("commit")){
            customFeedDao.saveUserInfo(clientId,jsonStr);

            customFeedDao.updateLoanInfo(new CustomFeed(){
                {
                    setId(loanId);
                    setAppliedStatus(1);
                }
            });
        } else if (opt.equals("save")) {
            customFeedDao.saveUserInfo(clientId,jsonStr);
            customFeedDao.updateLoanInfo(new CustomFeed(){
                {
                    setId(loanId);
                    setAppliedStatus(1);
                }
            });
        }else if  (opt.equals("giveUp")){
            customFeedDao.saveUserInfo(clientId,jsonStr);
            customFeedDao.updateLoanInfo(new CustomFeed(){
                {
                    setId(loanId);
                    setAppliedStatus(2);
                }
            });
        }else {
            return false;
        }


        return true;
    }

    @Override
    public CustomFeed selectFeedById(int feedId) {

        CustomFeed feedById = customFeedDao.findFeedById(feedId);
        //根据申请状态编号设置申请状态描述
        
        feedById.setApplicantStatus(customFeedDao.getApplicantStatus(feedById.getAppliedStatus()));
        //根据产品编号设置产品_渠道名（如信贷（10001））
        feedById.setProChan(feedById.getProductionName() + '(' + feedById.getChannelId() + ')');
        //根据还款方式编号设置还款方式
        feedById.setPaymentStatusValue(customFeedDao.getPaymentStatus(feedById.getPaymentStatus()));
        return feedById;
    }

    @Override
    @Transactional
    public Map<String, Object> addNewFeedS1(CustomFeed customFeed) {
        LoanInfo loanInfo = new LoanInfo();
        //获得初始loan_info表中的最大id对应的贷款编号
        Long initialLoanNum = customFeedDao.getInitialLoanNum();
        //设置新的申请编号
        String orderNumMax = customFeedDao.getLastestOrderNum();
        String prefix = orderNumMax.replaceAll("[^(A-Za-z)]", "").toUpperCase();
        int parseInt = Integer.parseInt(orderNumMax.replaceAll("[^(0-9)]", ""));
        parseInt++;
        loanInfo.setOrderNum(prefix + parseInt);
        //设置渠道ID
        loanInfo.setChannelId(customFeedDao.getChannelId(customFeed.getChannelName()));
        //设置产品ID
        Integer productionId = customFeedDao.getProductionId(customFeed.getProductionName());
        loanInfo.setProductionId(productionId);

        //设置进件状态
        loanInfo.setApplicantStatus(0);
        //向订单表插入上述数据
        Integer result1 = customFeedDao.addNewFeedS1ForLoanInfo(loanInfo);
        //获得新插入订单的id
        Integer newIdForLoan = customFeedDao.getMaxIdForLoan();
        Integer result2 = 0;
        //插入用户表中
        //判断是否是已存在的用户，之后再新增
        List<Client> clients = customFeedDao.findAllClient();
        int flag = 0;
        for (Client c : clients) {
            if (c.getCitizenIdentity().equals(customFeed.getCitizenIdentity()) && c.getPhone().equals(customFeed.getPhone())) {
                ++flag;
                continue;

            }
        }
        if (flag == 0) {
            customFeed.setCreateTime( new Date());
            customFeed.setLastTime(new Date());
            result2 = customFeedDao.addNewFeedS1ForClientInfo(customFeed);
        }
        //上述行为成功后，设置loan_info订单表里新增订单对应的用户id及贷款编号
        Integer newClientId = customFeedDao.getMaxIdForClient();
        System.out.println("newClientId:"+newClientId);
        CustomFeed temp = new CustomFeed();
        temp.setClientId(newClientId);
        temp.setLoanNum(++initialLoanNum);
        temp.setId(newIdForLoan);
        customFeedDao.updateLoanInfo(temp);
        //返回新增订单的贷款编号，和渠道-产品的组合名

        Long finalMaxIdOfLoan = initialLoanNum;
        //获得产品类型，组合新的名称
//            String productionType = customFeedDao.getProductionTypeById(productionId);
        String channelProduction = "信贷" + "(" + productionId + ")";
        return new HashMap<String, Object>() {{
            put("newFeedClientId", newClientId);
            put("newFeedLoanId",newIdForLoan);
            put("newFeedLoanNum", finalMaxIdOfLoan);
            put("newFeedProductName", channelProduction);
        }};
    }

    @Override
    public List<String> findChannel() {
        return customFeedDao.findChannel();
    }

    @Override
    public List<String> finProduction(String channelName) {
        System.out.println(channelName + "******");
        return customFeedDao.findProduction(channelName);
    }

    @Override
    public List<String> findApplicantStatus() {
        return customFeedDao.findApplicantStatus();
    }

    @Override
    public List<String> findOrigin() {
//         customFeedDao.findOrigin();
        return null;
    }

    @Override
    public List<String> findPrincipal() {
        return customFeedDao.findPrincipal();
    }

    @Transactional
    @Override
    public Boolean updateFeedPrincipal(CustomFeed customFeed) {
        customFeed.setClientId(customFeedDao.getClientIdById(customFeed.getId()));

        Integer updateClientInfo = customFeedDao.updateClientInfo(customFeed);
        customFeed.setPrincipalId(customFeedDao.findPrincipalByName(customFeed));
        Integer updateLoanInfo = customFeedDao.updateLoanInfo(customFeed);

        if (updateClientInfo + updateLoanInfo > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<CustomFeed> exportList() {
        List<CustomFeed> allCustomFeed = customFeedDao.findAllCustomFeed(null);
        for (CustomFeed customfeed : allCustomFeed) {

            customfeed.setApplicantStatus(customFeedDao.getApplicantStatus(customfeed.getAppliedStatus()));
        }
        return allCustomFeed;
    }
}
